<template>
  <div class="handnote">
    <van-nav-bar fixed>
      <template #title>
        <span style="font-size: 20px; font-weight: 600">手记精选</span>
      </template>
      <template #right>
        <i
          class="iconfont icon-pinglun"
          style="font-size: 26px; font-weight: 600"
        ></i>
      </template>
    </van-nav-bar>
    <div class="itembox" ref="itembox">
      <div
        class="item"
        v-for="(i, index) in noteData"
        :key="index"
        @click="onclick(i.id)"
      >
        <img
          v-if="i.images"
          class="bigimg"
          :src="i.images[0] | picUrl"
          alt=""
        />
        <span class="title">{{ i.title }}</span>
        <div class="user">
          <img class="headimg" :src="i.user.avatar | picUrl" alt="" />
          <span class="username">{{ i.user.username }}</span>
          <span class="liked"
            >{{ i.user.count.count_liked }}
            <i class="iconfont icon-31dianzan"></i
          ></span>
        </div>
      </div>
    </div>
    <MyLoading v-if="!noteData.length"></MyLoading>
  </div>
</template>

<script>
import Vue from "vue";
import MyLoading from "@/components/MyLoading.vue";
import { NavBar } from "vant";
Vue.use(NavBar);
export default {
  data() {
    return {
      noteData: [],
      viewHeight: null,
      scollTop: null,
      totalHeight: null,
      page: 2,
      loading: true,
      addList: true,
      itemboxWidth: null,
    };
  },
  components: {
    MyLoading,
  },
  created() {
    this.axios.get("https://apis.netstart.cn/xpc/notes").then((res) => {
      this.noteData = res.data.data.list;
    });
  },
  mounted() {
    window.addEventListener("scroll", this.handleScrollx, true);
    //可视区域高度
    this.viewHeight = document.documentElement.clientHeight;
    this.itemboxWidth = this.$refs.itembox.offsetWidth;
  },
  watch: {
    noteData: function (n) {
      this.waterFull();
    },
  },
  methods: {
    onclick(id) {
      this.$router.push({ path: "/notedetail", query: { id: id } });
    },
    waterFull() {
      this.$nextTick(() => {
        // 获取所有需要瀑布流的元素
        let oItem = this.$refs.itembox.querySelectorAll(".item");
        // 获得每一项的宽度
        let itemWidth = oItem[0].offsetWidth;
        // 计算每行能放几个item
        let num = Math.floor(this.itemboxWidth / itemWidth);
        console.log(num);
        // 初始化保存item距离顶部的高度的数组
        var harr = [];
        oItem.forEach((a, b) => {
          // 第一列正常排列
          if (b < num) {
            var timer = setInterval(function () {
              if (a.querySelector("img").complete) {
                setTimeout(() => {
                  harr.push(a.offsetHeight + 15);
                  console.log(harr);
                }, 200);
                  clearInterval(timer);
              }
            }, 50);
            // 其他的瀑布流
          } else {
            var ll = () => {
              // harr[hindex]+=a.offsetHeight
              var kkk = setInterval(() => {
                // 判断图片是否加载完成，不然计算高度会有偏差
                if (a.querySelector("img").complete) {
                  // 图片加载完成后再延迟两秒计算高度
                  setTimeout(()=>{
                    var minh = Math.min(...harr);
                    // 获取距离顶部高度小的是数组的第几项
                    // 因为每行只放得下两项，根据距离顶部高度小的是数组的第一项还是第二项然后定位
                    var hindex = this.getHindex(minh, harr);
                    console.log(harr);
                    console.log(hindex);
                    // 给样式
                    a.style.position = "absolute";
                    if (hindex == 0) {
                      a.style.left = 0 + "px";
                    } else {
                      a.style.left = itemWidth+7 + "px";
                    }
                    a.style.top = minh + "px";
                    harr[hindex] += a.offsetHeight + 15;
                    this.$refs.itembox.style.height =
                    Math.max(...harr) + 60 + "px";
                  },500)
                  clearInterval(kkk);
                }
              }, 50);
            };
            var timer = setInterval(() => {
              if (harr.length >= 2) {
                ll();
                clearInterval(timer);
              }
            }, 50);
          }
        });
        console.log(harr);
      });
    },
    getHindex(minh, harr) {
      let num;
      harr.forEach((a, b) => {
        if (a == minh) {
          num = b;
        }
      });
      return num;
    },
    handleScrollx() {
      //滚动高度
      this.scollTop = document.documentElement.scrollTop;
      //可滚动高度
      this.totalHeight = document.documentElement.scrollHeight;
      if (
        this.viewHeight + this.scollTop > this.totalHeight - 10 &&
        this.loading &&
        this.addList
      ) {
        this.addList = false;
        this.axios
          .get("https://apis.netstart.cn/xpc/notes?page=" + this.page)
          .then((res) => {
            this.noteData.push(...res.data.data.list);
            this.page++;
            setTimeout(() => {
              this.addList = true;
            }, 2000);
          })
          .catch(() => {
            this.loading = false;
            this.addList = false;
          });
      }
    },
  },
};
</script>

<style lang="less" scoped>
.handnote {
  width: 100vw;
  padding-top: 47px;
  background-color: #f7f7f7;
  .itembox {
    width: 100vw;
    height: 100%;
    padding: 10px 0;
    position: relative;
    background-color: #f7f7f7;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    align-items: flex-start;
    .item {
      // position: absolute;
      flex-shrink: 0;
      flex-grow: 0;
      width: 49%;
      height: auto;
      display: inline-block;
      background-color: #fff;
      border-radius: 10px;
      overflow: hidden;
      .bigimg {
        width: 100%;
        height: auto;
        display: block;
      }
      .title {
        display: inline-block;
        font-weight: 600;
        font-size: 14px;
        margin: 10px 15px;
      }
      .user {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0px 15px 15px 15px;
        color: #999;
        font-size: 13px;
        font-weight: 500;
        .headimg {
          width: 25px;
          height: 25px;
          border-radius: 50%;
          margin-right: 5px;
        }
        .username {
          flex: 1;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }
  }
}
</style>